<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*总数字资源类型model*/

class ResourceTypeCxzx extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_type_cxzx';

    /**
     *添加所有数据类型到本地数据库
     * @param data 类型数据
     */
    public function addData($data)
    {
        $clc = !empty($data['Clc']) ? $data['Clc'] : []; //获取中图法分类信息集合
        $subject = !empty($data['Subject']) ? $data['Subject'] : []; //获取学科分类信息集合
        foreach ($clc as $key => $val) {
            $this->addType(1, $val, 1, 0);
        }
        foreach ($subject as $key => $val) {
            $this->addType(2, $val, 1, 0);
        }
    }

    /**
     *添加数据到
     */
    public function addType($node, $data, $level, $parent_id)
    {
        $obj = new Self();
        $original_id = $data['Id'];
        $is_exists = $obj->where('node', $node)->where('original_id', $original_id)->first();
        if ($is_exists) {
            $is_exists->type_name = $data['Name'];
            $is_exists->level = $level;
            $is_exists->parent_id = $parent_id;
            $is_exists->is_del = 1;
            $is_exists->save();
        } else {
            $obj->node = $node;
            $obj->original_id = $original_id;
            $obj->type_name = $data['Name'];
            $obj->level = $level;
            $obj->parent_id = $parent_id;
            $obj->is_del = 1;
            $obj->letter = get_first_charter($data['Name']);
            $obj->save();
        }
        if (!empty($data['Children'])) {
            foreach ($data['Children'] as $key => $val) {
                $this->addType($node, $val, $level + 1, $original_id);
            }
        }
    }
}
